package com.casic.ops.handler.pipeline;

import cn.hutool.core.io.FileUtil;
import com.casic.ops.annotation.IgnoreLog;
import com.casic.ops.configs.ApplicationContextUtil;
import com.casic.ops.entity.dto.FileDownloadDTO;
import com.casic.ops.entity.dto.UserDTO;
import com.casic.ops.service.api.FileDownloadService;
import com.casic.ops.utils.Currents;
import com.casic.ops.utils.OpsAssert;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName ops
 * @Description 机器终端日志的信息返回,暂时又不用了
 * @Author mianbin
 * @Date 2022/6/21 17:15
 * @Version 1.0
 **/
@Slf4j
@Component
@ServerEndpoint("/ops/terminal/log/{token}")
public class MachineTerminalLoggerSocketHandler {

    private FileDownloadService fileDownloadService;

    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    @OnOpen
    @IgnoreLog
    public void onOpen(Session session, @PathParam(value = "token") String token) {

        //
        // 这里开始返回东西 , 直接返回 , 前端不会有交互输入任何东西.
        //
        String path = Optional.ofNullable(token)
                .map(var -> fileDownloadService.getPathByDownloadToken(var))
                .map(FileDownloadDTO::getFilePath).orElse(null);

        if (Objects.isNull(fileDownloadService)) {
            this.fileDownloadService = ApplicationContextUtil.getBean(FileDownloadService.class);
        }
        try {
            String data = FileUtils.readFileToString(new File(path) , "utf-8");
            session.getBasicRemote().sendText(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("用户:{} 建立链接 , 并发送数据完毕");
    }

    @OnClose
    @IgnoreLog
    public void onClose(@PathParam(value = "username") String userName) {
        System.out.println(userName + " 断开webSocket连接！");
    }

    @OnMessage
    @IgnoreLog
    public void onMessage(String message) throws IOException {
        log.info("收到详细message", message);
    }

    @OnError
    @IgnoreLog
    public void onError(Session session, Throwable throwable) {
        log.info("发生错误");
        throwable.printStackTrace();
    }


}
